import { defineComponent, reactive, onMounted, watch, markRaw, nextTick } from 'vue'
import * as echarts from 'echarts'
import styles from '../../index.module.scss'
import type { DimMatrixChartDataListType } from './typings'

export default defineComponent({
  props: ['dataList', 'id'],
  setup(
    props: { dataList: any; id: string } = {
      dataList: [],
      id: 'contents'
    }
  ) {
    const state = reactive<DimMatrixChartDataListType>({
      dataset: {
        source: []
      }
    })

    watch(
      () => props.dataList,
      () => {
        lineInit()
      }
    )

    onMounted(() => {
      nextTick(() => {
        createLineInit()
      })
    })

    // methods
    // 初始化echarts实例
    const createLineInit = () => {
      const dom = document.getElementById(props.id)
      state.myChart = markRaw(echarts.init(dom!))
      lineInit()
    }

    // 绘图
    const lineInit = () => {
      // 绘制图表 柱宽不定
      state.myChart.clear()
      state.myChart.setOption({
        title: {
          text: '当日灯杆24小时调光曲线图',
          right: 16
        },
        color: ['#c4a6ff', '#1cebd4', '#65afff'],
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: props.dataList?.hour
        },
        yAxis: {
          name: '调光值',
          type: 'value'
        },
        series: [
          {
            data: props.dataList?.dim,
            type: 'line'
          }
        ]
      })

      // 建议加上以下这一行代码，不加的话，当浏览器窗口缩小时，超过div界限
      window.addEventListener('resize', function () {
        state.myChart.resize()
      })
    }

    return () => (
      <div class={styles['line-chart']}>
        <div id={props.id} class={styles['statistics-map']}></div>
      </div>
    )
  }
})
